package com.itsu.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itsu.domain.*;
import com.itsu.service.DeptService;
import com.itsu.service.Impl.DeptServiceImpl;
import com.itsu.service.Impl.RoleServiceImpl;
import com.itsu.service.Impl.UserServiceImpl;
import com.itsu.service.RoleService;
import com.itsu.service.UserService;
import com.itsu.utils.BeanUtil;
import com.itsu.utils.MD5Util;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@WebServlet("/system/user")
public class UserController extends HttpServlet {

    private UserService userService = new UserServiceImpl();
    private DeptService deptService = new DeptServiceImpl();
    private RoleService roleService = new RoleServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String operation = req.getParameter("operation");
        if ("list".equals(operation)) {
            showList(req, resp);
        } else if ("login".equals(operation)) {
            login(req, resp);
        } else if ("home".equals(operation)) {
            home(req, resp);
        } else if ("toAdd".equals(operation)) {
            toAdd(req, resp);
        } else if ("save".equals(operation)) {
            save(req, resp);
        } else if ("toEdit".equals(operation)) {
            toEdit(req, resp);
        } else if ("edit".equals(operation)) {
            edit(req, resp);
        } else if ("delete".equals(operation)) {
            delete(req, resp);
        } else if ("userRoleList".equals(operation)) {
            userRoleList(req, resp);
        } else if ("updateRoleUser".equals(operation)) {
            updateRoleUser(req, resp);
        }
    }

    private void showList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNum = 1;
        int pageSize = 10;
        if (!StringUtils.isNullOrEmpty(req.getParameter("page"))) {
            pageNum = Integer.parseInt(req.getParameter("page"));
        }
        PageInfo<User> pageInfo = userService.findAll(pageNum, pageSize);

        req.setAttribute("page", pageInfo);

        req.getRequestDispatcher("/WEB-INF/pages/system/user/list.jsp").forward(req, resp);
    }

    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Dept> deptList = deptService.findAll();
        req.setAttribute("deptList", deptList);
        req.getRequestDispatcher("/WEB-INF/pages/system/user/add.jsp").forward(req, resp);
    }

    private void save(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = BeanUtil.fillBean(req, User.class, "yyyy-MM-dd");
        user.setId(UUID.randomUUID().toString());
        user.setPassword(MD5Util.md5(user.getPassword()));
        userService.save(user);
        resp.sendRedirect(req.getContextPath() + "/system/user?operation=list");
    }


    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        User user = userService.findById(id);

        List<Dept> deptList = deptService.findAll();
        req.setAttribute("deptList", deptList);
        req.setAttribute("user", user);
        req.getRequestDispatcher("/WEB-INF/pages/system/user/update.jsp").forward(req, resp);
    }

    private void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = BeanUtil.fillBean(req, User.class, "yyyy-MM-dd");
        userService.update(user);

        resp.sendRedirect(req.getContextPath() + "/system/user?operation=list");
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = BeanUtil.fillBean(req, User.class, "yyyy-MM-dd");
        userService.delete(user);

        resp.sendRedirect(req.getContextPath() + "/system/user?operation=list");
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String message = null;
        List<String> moduleUrl = null;

        User u = userService.findByEmail(email);

        if (u != null) {
            List<Module> list = userService.findModulesById(u.getId());
            moduleUrl = new ArrayList<>();
            for (Module module : list) {
                moduleUrl.add(module.getCurl());
            }
            if (MD5Util.md5(password).equals(u.getPassword())) {
                req.getSession().setAttribute("user", u);
                req.getSession().setAttribute("modules", list);
                System.out.println(moduleUrl);
                req.getSession().setAttribute("moduleCUrl", moduleUrl);
                req.getRequestDispatcher("/WEB-INF/pages/home/main.jsp").forward(req, resp);
                return;
            } else {
                message = "密码错误!";
            }
        } else {
            message = "用户名错误!";
        }

        req.setAttribute("error", message);
        req.getRequestDispatcher("/login.jsp").forward(req, resp);

    }

    private void home(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/pages/home/home.jsp").forward(req, resp);
    }

    private void userRoleList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        User u = userService.findById(id);
        List<RoleTree> list = roleService.findRoleByUserId(id);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(list);

        req.setAttribute("user", u);
        req.setAttribute("json", json);
        req.getRequestDispatcher("/WEB-INF/pages/system/user/author.jsp").forward(req, resp);
    }

    private void updateRoleUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userId = req.getParameter("id");
        String roleIds = req.getParameter("roleIds");
        String[] split = roleIds.split(",");
        userService.deleteRoleUserByUserId(userId);
        for (String roleId : split) {
            userService.addRoleUser(userId, roleId);
        }

        resp.sendRedirect(req.getContextPath() + "/system/user?operation=list");
    }
}
